package com.gem.sms.web;

import com.gem.sms.entity.Student;
import com.gem.sms.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/stu")
@SessionAttributes("student")
public class StudentController {
    @Autowired
    StudentService studentService;

    @GetMapping("/index")
    public String index()
    {
        return"login";
    }

    @RequestMapping("/login")
    @ResponseBody//表示该方法响应的是一组数据 而不执行跳转功能
    public String login(Model model, String stuNo, String password, String rememberMe,String uCode ,HttpServletRequest request, HttpServletResponse response)
    {
        HttpSession session = request.getSession();
        //获取系统验证码
        String sCode = (String) session.getAttribute("validationCode");
        if (sCode.equalsIgnoreCase(uCode)) {
            Student student=studentService.canLogin(stuNo,password);
            if (student != null) {
                if ("1".equals(rememberMe)) {
                    //说明要使用记住我功能
                    Cookie cookie = new Cookie("stuInfo", stuNo + ":" + password);
                    cookie.setMaxAge(7 * 24 * 60 * 60);
                    response.addCookie(cookie);
                    System.out.println("保存cookie");
                } else {
                    //说明不要使用Cookie记录用户登录信息
                    Cookie[] cookies = request.getCookies();
                    Cookie cookie = getCookie(cookies, "stuInfo");
                    if (cookie != null) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
                model.addAttribute("student", student);
                return "1";
            }
            return "0";
        } else {
            return "2";//验证码错误
        }

    }

    @GetMapping("/logout")
    public String logout(SessionStatus status)
    {
        status.setComplete();
        return "redirect:index";
    }

    private Cookie getCookie(Cookie[] cookies, String name) {
        Cookie cookie = null;
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (name.equals(c.getName())) {
                    cookie = c;
                    break;
                }
            }
        }
        return cookie;
    }
}
